package com.github.livebase.util.http;

import android.util.Log;

import com.github.livebase.log.LogUtil;
import com.github.livebase.log.LoggerFactory;
import com.github.livebase.util.StringKeyValuePairs;
import com.github.livebase.util.base.ByteArray;
import com.github.livebase.util.base.IOUtil;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.List;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

/**
 * @ClassName ClientUtil
 * @description:
 * @author: biao532
 * @create: 2024-02-18 17:58
 * @Version 1.0
 **/
public class ClientUtil {
    public static CloseableResponse sendHttpRequest(String method, URL url, List<StringKeyValuePairs> headers, InputStream dataInputstream) {
        return sendHttpRequest(method, url, headers, dataInputstream, true);
    }
    public static CloseableResponse sendHttpRequest(String method, URL url, List<StringKeyValuePairs> headers, InputStream dataInputstream, boolean verifierSSL) {
        if (!verifierSSL) {
            LoggerFactory.getLogger(ClientUtil.class).warn("ClientUtil", "do not verify ssl connect");
            return sendHttpRequest(method, url, headers, dataInputstream, getSSLSocketFactory(),
                    (hostname, session) -> true);
        }
        return sendHttpRequest(method, url, headers, dataInputstream, null, null);
    }
    public static CloseableResponse sendHttpRequest(String method, URL url, List<StringKeyValuePairs> headers, InputStream dataInputstream, SSLSocketFactory socketFactory, HostnameVerifier verifier) {
        HttpURLConnection connection = null;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        CloseableResponse response = null;
        try {
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod(method);
            for (StringKeyValuePairs p : headers) {
                connection.setRequestProperty(p.getKey(), p.getValue());
            }
            if (connection instanceof HttpsURLConnection) {
                if (socketFactory != null) {
                    ((HttpsURLConnection)connection).setSSLSocketFactory(socketFactory);
                }
                if (verifier != null) {
                    ((HttpsURLConnection)connection).setHostnameVerifier(verifier);
                }
            }
            connection.setDoOutput(dataInputstream != null);
            connection.setDoInput(true);
            connection.connect();
            if (dataInputstream != null) {
                outputStream = connection.getOutputStream();
                IOUtil.transferTo(dataInputstream, outputStream);
            }
            response = new CloseableResponse();
            response.setCode(connection.getResponseCode());
            response.setHeader(connection.getHeaderFields());
            inputStream = connection.getInputStream();
            ByteArray byteArray = IOUtil.transferToByteArray(inputStream, connection.getContentLength());
            Log.i("ClientUtil", "s=" + byteArray);
            response.setStream(byteArray.toInputStream());
            return response;
        }
        catch (IOException e) {
            LoggerFactory.getLogger(ClientUtil.class).warn("ClientUtil", e, LogUtil.ERROR_OCCURRED + " response is {}", method + " " + url, response);
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException ex) {
                    LoggerFactory.getLogger(ClientUtil.class).warn("ClientUtil", ex, LogUtil.ERROR_OCCURRED, method +" " + url);
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException ex) {
                    LoggerFactory.getLogger(ClientUtil.class).warn("ClientUtil", ex, LogUtil.ERROR_OCCURRED, method +" " + url);
                }
            }
        }
        return response;
    }

    public static String post(String url, InputStream input, List<StringKeyValuePairs> headers) throws IOException {
        CloseableResponse response = sendHttpRequest("POST", new URL(url), headers, input);
        if (response.getCode() == 200) {
            return IOUtil.toString(response.getStream());
        }
        return null;
    }
    private static SSLSocketFactory getSSLSocketFactory() {
        try {
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, getTrustManager(), new SecureRandom());
            return sslContext.getSocketFactory();
        }
        catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    //获取TrustManager
    private static TrustManager[] getTrustManager() {
        TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[]{};
            }
        }};
        return trustAllCerts;
    }
}
